import { ref, onMounted } from "vue"
//导入Http请求
import { Http } from "@/http/users.js"
//引入信息提示
import { ElMessage } from "element-plus"
import router from "../../../router"
//导入store
import { useUserStore } from "@/stores/users.js"
const store = useUserStore()

export const useLogin = () => {
  //自定义验证码规则
  /* 自定义验证码规则 */
  const validateVerifycode = (rule, value, callback) => {
    if (value === "") {
      callback(new Error("请输入验证码"))
    } else if (value !== identifyCode.value) {
      callback(new Error("验证码不正确!"))
    } else {
      callback()
    }
  }
  //自定义两次密码不一致规则
  const validatePass = (rule, value, callback) => {
    if (value === "") {
      callback(new Error("请输入密码"))
    } else {
      if (userMsg.value.checkpassword !== "") {
        if (!loginForm.value) return
        loginForm.value.validateField("checkpassword", () => null)
      }
      callback()
    }
  }
  const validatePass2 = (rule, value, callback) => {
    if (value === "") {
      callback(new Error("请确认密码"))
    } else if (value !== userMsg.value.password) {
      callback(new Error("两次密码不一致"))
    } else {
      callback()
    }
  }
  //验证码数据
  const identifyCodes = ref("1234567890abcdefghijklmnopqrstuvwxyz")
  const identifyCode = ref("")
  const randomNum = (min, max) => {
    return Math.floor(Math.random() * (max - min) + min)
  }
  // 切换验证码
  const refreshCode = () => {
    identifyCode.value = ""
    makeCode(identifyCodes.value, 4)
  }
  const makeCode = (o, l) => {
    for (let i = 0; i < l; i++) {
      identifyCode.value +=
        identifyCodes.value[randomNum(0, identifyCodes.value.length)]
    }
    console.log(identifyCode.value)
  }

  //用户信息
  const userMsg = ref({
    username: "",
    password: "",
    checkpassword: "",
    verifycode: "",
  })
  //验证码挂载
  onMounted(() => {
    identifyCode.value = ""
    makeCode(identifyCodes.value, 4)
    history.pushState(null, null, document.URL)
    if (window.history && window.history.pushState) {
      window.addEventListener("popstate", function () {
        window.history.pushState("forward", null, "")
        window.history.forward(1)
      })
      window.history.pushState("forward", null, "") //在IE中必须得有这两行
      window.history.forward(1)
    }
  })
  //表单实例
  const loginForm = ref()
  //记录登录或者注册的状态
  const titleFlag = ref("登录")
  //表单验证规则
  const loginRules = ref({
    username: [
      {
        required: true,
        message: "请输入用户名",
        trigger: "blur",
      },
      { min: 2, max: 6, message: "长度在3~8个字符", trigger: "blur" },
    ],
    password: [
      {
        required: true,
        // message: "请输入密码",
        trigger: "blur",
        validator: validatePass,
      },
      { min: 4, max: 16, message: "长度在4~16个字符", trigger: "blur" },
    ],
    checkpassword: [
      {
        required: true,
        // message: "请输入密码",
        trigger: "blur",
        validator: validatePass2,
      },
      { min: 4, max: 16, message: "长度在4~16个字符", trigger: "blur" },
    ],
    verifycode: [
      {
        required: true,
        trigger: "blur",
        validator: validateVerifycode,
      },
    ],
  })
  //验证表单
  const submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
      if (valid) {
        if (titleFlag.value == "注册") {
          if (userMsg.value.password == userMsg.value.checkpassword) {
            let data = await Http.addUsers({
              username: userMsg.value.username,
              password: userMsg.value.password,
              type: 0,
            })
            if (data.code == 200) {
              ElMessage.success("注册成功,请等待管理员审核")
              titleFlag.value = "登录"
              userMsg.value = { username: "", password: "" }
            } else {
              ElMessage.error("用户名已占用,请重新注册")
              return
            }
          } else {
            ElMessage.error("两次密码不一致,请重新输入")
          }
        } else {
          let data = await Http.userLogin(userMsg.value)
          if (
            data.code == 200 &&
            data.result.deleted == 0 &&
            (data.result.type == 1 || data.result.type == 2)
          ) {
            ElMessage.success("登录成功")
            //将用户信息存入store
            store.saveUser(
              data.token,
              data.result.username,
              data.result.type,
              data.result.id,
              data.result.password
            )
            // console.log(store)
            router.push("/home")
          } else if (data.code == 203) {
            ElMessage.error("用户已注销")
            return
          } else if (data.result.type == 0) {
            ElMessage.error("管理员正在审核")
            //调为下线
            Http.underLine(data.result.id)
          } else {
            ElMessage.error("用户名或者密码错误")
            return
          }
        }
      } else {
        console.log("error submit!", fields)
      }
    })
  }
  // 切换登录或者注册状态
  const toRegister = () => {
    titleFlag.value = "注册"
  }
  const toLogin = () => {
    titleFlag.value = "登录"
  }
  return {
    userMsg,
    loginRules,
    submitForm,
    loginForm,
    toRegister,
    titleFlag,
    toLogin,
    identifyCode,
    refreshCode,
  }
}
